/*
 * Region.cpp
 *
 *  Created on: 22-Feb-2014
 *      Author: dev
 */

#include "Region.h"
#include <stddef.h>

namespace tf {

Region::Region(Rectangle* rect) {
	rects.push_back(std::make_pair(rect, true));

}

Rectangle Region::bounds() {

	size_t minx, miny, maxx, maxy;
	maxx = maxy = 0;
	minx = miny = std::string::npos;

	for (size_t i = 0; i < rects.size(); i++) {
		std::pair<Rectangle*, bool> rect = rects[i];

		if (!rect.second) { // -ve rect are not counted in bounds
			continue;
		}

		if (minx > (size_t) rect.first->left()) {
			minx = rect.first->left();
		}

		if (miny > (size_t) rect.first->top()) {
			miny = rect.first->top();
		}

		if (maxx < (size_t) rect.first->right()) {
			maxx = rect.first->right();
		}

		if (maxy < (size_t) rect.first->bottom()) {
			maxy = rect.first->bottom();
		}
	}

	Rectangle bound;
	bound.set(minx, miny, maxx, maxy);
	return bound;
}

void Region::add(Rectangle* rect) {
	rects.push_back(std::make_pair(rect, true));
}

void Region::remove(Rectangle* rect) {
	if (!bounds().intersect(*rect)) {
		rects.push_back(std::make_pair(rect, false));
	} else {
		cout << "ERR: rects do not intersect" << endl;
	}
}

bool Region::interset(Region reg) {
	return bounds().intersect(reg.bounds());

}

string Region::str() {
	stringstream ss;
	ss << "< ";
	for (size_t i = 0; i < rects.size(); i++) {
		ss << rects[i].first->str();
		ss << ", ";
	}
	ss << ">";
	return ss.str();
}

Region::~Region() {

}

} /* namespace tf */
